console.log("content_script.js");

var imageCode = document.getElementById("imageCode");

var yzmImg = document.getElementsByClassName("yzm_img_img")[0];

var pageType = '';
var yzm_src = '';

if(imageCode){
    yzm_src = imageCode.getAttribute('src');
    pageType = 'zb';
}else if(yzmImg){
    yzm_src = yzmImg.getAttribute('src');
    pageType = 'yy';
}

var yzm_url ;
if(yzm_url && yzm_url!=''){
    yzm_src = yzm_url;
}else{
    yzm_url = yzm_src;
}

var xhr = new XMLHttpRequest();
xhr.open('GET', yzm_src, true);
xhr.responseType = "blob";
xhr.setRequestHeader("client_type", "DESKTOP_WEB");
xhr.onload = function() {
    if (this.status == 200) {
        var blob = this.response;

        let reader = new FileReader()
        reader.addEventListener('load', () => {
            console.log(reader.result);

            sogouExplorer.runtime.sendMessage({imgObj: reader.result},function (response) {
                console.log('content get response:',response);
                if(response && response.resp){

                    if(pageType == 'zb'){
                        document.getElementById("validCode").value = response.resp;
                    }else if(pageType = 'yy'){
                        document.getElementById("myInput").value = response.resp;
                    }
                }
            });
        })
        reader.readAsDataURL(blob)

        var img = null;
        if(pageType == 'zb'){
            img = document.getElementById("imageCode");
        }
        else if(pageType = 'yy'){
            img = document.getElementsByClassName("yzm_img_img")[0];
        }
        
        img.onload = function(e) {
            window.URL.revokeObjectURL(img.src); 
        };
        img.src = window.URL.createObjectURL(blob);

    }
}
xhr.send();
